package me.xinping.record.ui

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_splash.*
import me.xinping.libs.utils.PermissionUtils
import me.xinping.libs.utils.ToastHelper
import me.xinping.record.BuildConfig
import me.xinping.record.R
import me.xinping.record.config.AppInitialization
import me.xinping.record.extension.show
import java.lang.ref.WeakReference


class SplashActivity : AppCompatActivity() {
    private var startTime: Long = System.currentTimeMillis()
    private var isEnter = false
    private lateinit var weakHandler: WeakHandler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        weakHandler = WeakHandler(this@SplashActivity)
        tv_version.text = getString(R.string.app_main_name).plus(" | ").plus(BuildConfig.VERSION_NAME)

        enterHome()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PermissionUtils.CODE_REQUEST_PERMISSION_SETTING) {
            PermissionUtils.checkPermission(this@SplashActivity, AppInitialization.recorderPermissions) {
                if (it) {
                    enterHome()
                } else {
                    ToastHelper.show(getString(R.string.no_permission_hint))
                    finish()
                }
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PermissionUtils.CODE_REQUEST_PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    val enable = shouldShowRequestPermissionRationale(permissions[0])
                    if (!enable) {
                        // 提示用户去应用设置界面手动开启权限
                        ToastHelper.show(getString(R.string.permission_desc))
                        PermissionUtils.startPermissionSetting(this)
                    } else {
                        ToastHelper.show(getString(R.string.permission_hint))
                        enterHome()
                    }
                } else {
                    enterHome()
                }
            }
        }
    }


    private fun enterHome() {
        PermissionUtils.checkPermission(
            this@SplashActivity, AppInitialization.recorderPermissions
        ) {
            if (it) {
                val costTime = System.currentTimeMillis() - startTime
                if (costTime > ENTER_HOME_DELAY) {
                    startMainActivity()
                } else {
                    weakHandler.sendEmptyMessageDelayed(0, ENTER_HOME_DELAY - costTime)
                }
            } else {
                ToastHelper.show(getString(R.string.permission_desc))
                PermissionUtils.startPermissionSetting(this)
            }
        }
    }

    private fun startMainActivity() {
        if (!isEnter) {
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            isEnter = true
            finish()
        }
    }

    class WeakHandler(activity: AppCompatActivity) : Handler() {
        private var reference: WeakReference<Activity> = WeakReference(activity)
        override fun handleMessage(msg: Message?) {
            val activity = reference.get()
            activity?.let {
                it.startActivity(Intent(it, MainActivity::class.java))
                it.finish()
            }
        }
    }

    companion object {
        /**
         * 进入首页延迟
         */
        const val ENTER_HOME_DELAY = 2_000L
    }

}
